# -*- coding: utf8 -*-

from project.sqlite3_db.table import Table

class TableImage( Table ):

    _table_name = "image"

    def create( self ):
        cur = self.getCursor()

        # Create table
        cur.execute(
            "CREATE TABLE IF NOT EXISTS image ("+
                "id INTEGER PRIMARY KEY, "+
                "file_id INTEGER, "+
                "size INTEGER, "+
                "is_gray INTEGER, "+
                "width INTEGER, "+
                "height INTEGER, "+
                "mime TEXT"+
            ")"
        )
        cur.execute(
            "CREATE INDEX IF NOT EXISTS files ON image (file_id)"
        )
        cur.close()
        return


    def insert_image( self, file_id, mime, size, is_gray,
                      width, height ):

        cur = self.getCursor()

        cur.execute("INSERT INTO image("+
                    "file_id, mime, size, is_gray, width, height"+
                    ") VALUES ("+
                    ":file_id, :mime, :size, :is_gray, :width, :height"+
                    ")", {
            "file_id":file_id,
            "mime":mime,
            "size":size,
            "is_gray":is_gray,
            "width":width,
            "height":height,
        })
        self.getConnection().commit()
        image_id = cur.lastrowid

        cur.close()
        return image_id

    def get_image(self, image_id):
        cur = self.getCursor()
        cur.execute(
            "SELECT * FROM image WHERE id=:value",
            {"value": image_id}
        )
        item = cur.fetchone()
        cur.close()
        if not item:
            item = False
        return item

    def get_images_count(self):
        cur = self.getCursor()
        cur.execute("SELECT COUNT(1) as c FROM image")
        item = cur.fetchone()
        cur.close()
        if not item:
            item = 0
        return item['c']

    def get_images_in_file_count(self, file_id):
        cur = self.getCursor()
        cur.execute("SELECT COUNT(1) as c FROM image WHERE file_id=:id", {"id":file_id})
        item = cur.fetchone()
        cur.close()
        if not item:
            item = {'c':0}
        return item['c']

    def remove_file_images(self, file_id):
        cur = self.getCursor()
        cur.execute("DELETE FROM image WHERE file_id=:id", {"id":file_id})
        self.getConnection().commit()
        rc = cur.rowcount
        cur.close()
        return rc

    def get_images(self, count, offset):
        cur = self.getCursor()
        cur.execute("SELECT * FROM image LIMIT :limit OFFSET :offset",
                {"limit":count,"offset":offset})
        items = cur.fetchall()
        cur.close()
        return items

    pass
